package com.atguigu.gulimall.auth.web;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberResponseVo;
import com.atguigu.gulimall.auth.config.RedisEx;
import com.atguigu.gulimall.auth.feign.MemberRegister;
import com.atguigu.gulimall.auth.feign.OssSmsService;
import com.atguigu.gulimall.auth.vo.LoginVo;
import com.atguigu.gulimall.auth.vo.RegisterVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author 满超
 * @date 2020/06/16
 **/
@Controller
public class AuthController {

    @Autowired
    OssSmsService ossSmsService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    MemberRegister memberRegister;


    @RequestMapping("/login.html")
    public String login(HttpSession session) {
        //从session取，redis里面
        Object attribute = session.getAttribute("username");
        if (attribute == null) {
            //没登录
            return "login";
        } else {
            return "redirect:http://www.gulimall.com";
        }
    }

    @RequestMapping("/register.html")
    public String reg() {
        return "register";
    }

    //通过短信获取验证码
    @ResponseBody
    @GetMapping("/sms/sendCode")
    public R sendSms(@RequestParam("phone") String phone) {

        //防止在规定时间内重复发送
        String redisCode = redisTemplate.opsForValue().get(RedisEx.SMS_CODE_CACHE_PREFIX + phone);
        if (!StringUtils.isEmpty(redisCode)) {
            long time = Long.parseLong(redisCode.split("_")[1]);
            if (System.currentTimeMillis() - time < 60000) {
                return R.error(10002,"请稍后再试");
            }
        }
        String code = UUID.randomUUID().toString().substring(0, 6);
        String cacheCode = code +"_" + System.currentTimeMillis();//截取6个字符
        System.out.println("手机号是："+phone + "验证码是：" + code);

        //将验证码存入缓存,sms:code:phone ->code,,三分钟有效
        redisTemplate.opsForValue().set(RedisEx.SMS_CODE_CACHE_PREFIX + phone, cacheCode,3, TimeUnit.MINUTES);

        //远程调用接口发送验证码
        //ossSmsService.sendCode(phone, code);
        return R.ok();
    }

    //注册，注册成功回到登录页面
    @PostMapping("/register")
    public String register(@Valid RegisterVo registerVo, BindingResult result, RedirectAttributes redirectAttributes){
        Map<String, String> errors = new HashMap<>();
        //jsr303错误校验
        if (result.hasErrors()) {
            for (FieldError fieldError : result.getFieldErrors()) {
                String field = fieldError.getField();
                String defaultMessage = fieldError.getDefaultMessage();
                errors.put(field,defaultMessage);
            }
            //使用重定向
            redirectAttributes.addFlashAttribute("errors",errors);
            System.out.println(errors);
            //校验不通过，重定向到注册页
            return "redirect:http://auth.gulimall.com/register.html";
        }

        //开始注册
        //1.校验验证码是否正确
        String code = registerVo.getCode();//前端验证码
        String redisCode = redisTemplate.opsForValue().get(RedisEx.SMS_CODE_CACHE_PREFIX + registerVo.getPhone());//缓存验证码
        if (!StringUtils.isEmpty(redisCode)) {
            if (code.equals(redisCode.split("_")[0])) {
                //删除验证码
                redisTemplate.delete(RedisEx.SMS_CODE_CACHE_PREFIX + registerVo.getPhone());
                //验证通过
                R register = memberRegister.register(registerVo);
                if (register.getCode() != 0){
                    //失败
                    errors.put("msg",register.getMsg());
                    redirectAttributes.addFlashAttribute("errors",errors);
                    //校验不通过，重定向到注册页
                    return "redirect:http://auth.gulimall.com/register.html";
                } else {
                    //重定向到登录页
                    return "redirect:http://auth.gulimall.com/login.html";
                }

            } else {
                errors.put("code","验证码出错");
                redirectAttributes.addFlashAttribute("errors",errors);
                //校验不通过，重定向到注册页
                return "redirect:http://auth.gulimall.com/register.html";
            }
        } else {
            errors.put("code","验证码超时");
            //使用重定向
            redirectAttributes.addFlashAttribute("errors",errors);
            //校验不通过，重定向到注册页
            return "redirect:http://auth.gulimall.com/register.html";
        }
    }


    @PostMapping("/login")
    public String login(LoginVo loginVo, RedirectAttributes attributes, HttpSession session){
        //远程登录
        R login = memberRegister.login(loginVo);
        if (login.getCode() != 0){
            //登录失败
            Map<String, String> errors = new HashMap<>();
            errors.put("msg",login.getMsg());
            attributes.addFlashAttribute("errors",errors);
            //校验不通过，重定向到登录
            return "redirect:http://auth.gulimall.com/login.html";
        } else {
            MemberResponseVo data = login.getData("data", new TypeReference<>() {
            });
            session.setAttribute("LoginUser", data);
            return "redirect:http://www.gulimall.com";
        }
    }
}